import prisma from "@/app/utils/prismadb";
import serverAuth from "@/app/utils/serverAuth";
import { NextResponse } from "next/server";
import {without} from 'lodash'

export const POST = async (req:Request)=>{
    try {
        const {currentUser} =  await serverAuth();
        const {movieId} = await req.json();
        const existingMovie = await prisma.movie.findUnique({
            where:{
                id:movieId
            }
        })
        if(!existingMovie){
            return NextResponse.json({ message:"Movie not found" }, { status: 404 })
        }
        const user = await prisma.user.update({
            where:{
                email:currentUser.email||""
            },
            data:{
                favoriteIds:{
                    push:movieId
                }
            }
        })
        return  NextResponse.json({ data: user }, { status: 200 })
    } catch (error) {
        console.log('current',error)
        return NextResponse.json({ message:"Internal server error" }, { status: 400 })
    }

}


export const DELETE = async (req:Request)=>{
    try {
        const {movieId} = await req.json();
        const {currentUser} =  await serverAuth();
       
        const existingMovie = await prisma.movie.findUnique({
            where:{
                id:movieId
            }
        })
        if(!existingMovie){
            return NextResponse.json({ message:"Movie not found" }, { status: 404 })
        }
        const favoriteIds = without(currentUser.favoriteIds,movieId)
        const user = await prisma.user.update({
            where:{
                email:currentUser.email||""
            },
            data:{
                favoriteIds
            }
        })
        return  NextResponse.json({ data: user }, { status: 200 })
    } catch (error) {
        console.log('current',error)
        return NextResponse.json({ message:"Internal server error" }, { status: 400 })
    }

}


export const GET = async ()=>{
    try {
        const {currentUser} =  await serverAuth();
         const movies = await prisma.movie.findMany({
            take:100,
            skip:0,
            where:{
                id:{
                    in:currentUser?.favoriteIds
                }
            }
         })
        return  NextResponse.json({ data: movies }, { status: 200 })
    } catch (error) {
        console.log('current',error)
        return NextResponse.json({ message:"Internal server error" }, { status: 400 })
    }

}







